package com.atguigu.lease.web.admin.config.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.ThreadLocalLoginUserContext;
import com.atguigu.lease.common.exception.LoginException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * Author ChenYongSheng
 * Date 2025/10/14 19:54
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    // 请求处理之前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("access_token");

        // 如果token过期解析不出来在这里会报错302 token过期，报错后前端检测到token错误直接跳转到首页
        Claims claims = JwtUtil.parseToken(token);

        Long userId = claims.get("userId", Long.class);
        String userName = claims.get("userName", String.class);

        LoginUser loginUser =new LoginUser(userId,userName);
        ThreadLocalLoginUserContext.setLoginUser(loginUser);


        return true;
    }

    // 请求处理完成之后
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        ThreadLocalLoginUserContext.remove();
    }

}
